/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[欢迎加盟知启蒙，一起邂逅框架梦]
 * 
 * https://www.zhiqim.com/gitcan/zhiqim/zhiqim_account.htm
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.zhiqim.account.action.connect;

import org.zhiqim.account.ZacSessionUser;
import org.zhiqim.account.api.connect.QQService;
import org.zhiqim.account.api.connect.QQUserInfo;
import org.zhiqim.account.dbo.user.UserAccount;
import org.zhiqim.account.dbo.user.UserInfo;
import org.zhiqim.account.presenter.UserPassportPresenter;
import org.zhiqim.httpd.HttpRequest;
import org.zhiqim.httpd.context.core.Action;
import org.zhiqim.kernel.Global;
import org.zhiqim.kernel.httpclient.HttpResult;
import org.zhiqim.kernel.json.Jsons;
import org.zhiqim.kernel.util.Urls;
import org.zhiqim.kernel.util.Validates;
import org.zhiqim.orm.ZTable;

/**
 * QQ互联回调，返回三个参数
 *
 * @version v1.4.1 @author zouzhigang 2018-4-20 新建与整理
 */
public class QQCallbackAction implements Action
{
    public void execute(HttpRequest request) throws Exception
    {
        String code = request.getParameter("code");
        String state = request.getParameter("state");
        String msg = request.getParameter("msg");
        
        if (Validates.isNotEmpty(msg))
        {//调用失败
            request.setRedirect("/index.htm", msg);
            return;
        }
        
        if(Validates.isEmpty(code))
        {//用户禁止授权
            request.getResponse().sendRedirect("/index.htm");
            return;
        }

        //1、获取访问令牌
        HttpResult result = QQService.getAccessToken(code);
        if(!result.isSuccess())
        {
            request.setRedirect("/index.htm", result.getResponseText());
            return;
        }
        
        //2.获取OPEN_ID
        String accessToken = Urls.get(result.getResponseText(), "access_token");
        result = QQService.getOpenId(accessToken);
        if(!result.isSuccess())
        {
            request.setRedirect("/index.htm", result.getResponseText());
            return;
        }
        
        //3.获取用户信息
        String openId = Jsons.getString(result.getResponseText(), "openid");
        result = QQService.getUserInfo(accessToken, openId);
        if (!result.isSuccess())
        {
            request.setRedirect("/index.htm", result.getResponseText());
            return;
        }
        
        
        //4.登录并跳转
        QQUserInfo qqUserInfo = new QQUserInfo().parse(result.getResponseText());
        qqUserInfo.setOpenId(openId);
        
        if (request.hasSessionUser(ZacSessionUser.class))
        {//执行绑定操作
            UserPassportPresenter.bindByConnect(request, qqUserInfo);
        }
        else
        {//跳转注册或者登录页面
            UserPassportPresenter.loginByConnect(request, qqUserInfo);
            UserAccount account = Global.get(ZTable.class).item(UserAccount.class, qqUserInfo.getUserAccount());
            if (account != null)
            {
                UserInfo user = Global.get(ZTable.class).item(UserInfo.class, account.getUserId());
                if (user != null && Validates.isNotEmpty(user.getUserName()))
                {//用户名不为空允许跳转登录
                    request.setRedirect(Urls.decodeUTF8(state));
                }
            }
        }
    }
}
